<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="name">
              <el-input v-model="searchForm.name" clearable placeholder="请输入分拣中心名称"></el-input>
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
                <el-option label="正常" value="1"></el-option>
                <el-option label="禁用" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.stop="search(true)">搜索</el-button>
              <el-button type="success" @click.stop="search">刷新</el-button>
              <el-button type="warning" @click.stop="add">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="table" border>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-row>
                <el-col :span="12">经度: {{ props.row.longitude }}</el-col>
                <el-col :span="12">纬度: {{ props.row.latitude }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="12">详细地址: {{ props.row.address }}</el-col>
                <el-col :span="12">描述: {{ props.row.detail }}</el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="ID" width="70"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <!-- <el-table-column prop="bind_name" label="管理员"></el-table-column> -->
          <!-- <el-table-column prop="driver_name" label="司机">
            <template slot-scope="scope">
              <span v-if="scope.row.driver_id == 0" style="color:#F56C6C">---</span>
              <span v-else>{{scope.row.driver_name}}-{{scope.row.role_name}}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="province" label="省"></el-table-column>
          <el-table-column prop="city" label="市"></el-table-column>
          <el-table-column prop="area" label="区"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.status == 1 ?'正常': '禁用'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="changeStatus(scope.row)">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="150">
            <template slot-scope="scope">
              {{scope.row.create_time|formatDate}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-dropdown trigger="click" @command="handleCommand">
                <el-button type="primary">
                  操作菜单<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{cmd:'edit', id:scope.row.id}">编辑</el-dropdown-item>
                  <el-dropdown-item :command="{cmd:'del', id:scope.row.id}">删除</el-dropdown-item>
                  <!-- <el-dropdown-item v-if="scope.row.driver_id === 0" :command="{cmd:'bindDriver', id:scope.row.id}">绑定司机</el-dropdown-item>
                  <el-dropdown-item v-else :command="{cmd:'unbindDriver', row:scope.row}">解绑司机</el-dropdown-item> -->
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page"
            :page-sizes="[10,20,30,40]" :page-size="searchForm.limit" layout="total, sizes, prev, pager, next, jumper" :total="count">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog title="编辑分拣中心" :visible.sync="editVisible" :before-close="handleClose('editForm')" width="800px">
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="rules">
          <el-form-item label="地图">
            <div id="editMap" style="min-height: 400px;width: 100%;"></div>
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="editForm.longitude" readonly></el-input>
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="editForm.latitude" readonly></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="pca">
            <v-distpicker :province="editForm.province" :city="editForm.city" :area="editForm.area" @province="onChangeEditProvince"
              @city="onChangeEditCity" @area="onChangeEditArea"></v-distpicker>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-row>
              <el-col :span="18">
                <el-input v-model="editForm.address" maxlength="255" show-word-limit clearable></el-input>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="searchAdd('editForm')">搜索</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="editForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="detail">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" maxlength="255" show-word-limit clearable v-model="editForm.detail">
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="管理员" prop="bind_id">
            <el-select v-model="editForm.bind_id" placeholder="请选择管理员" clearable>
              <el-option v-for="(item) in adminList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加分拣中心" :visible.sync="addVisible" :before-close="handleClose('addForm')" width="800px">
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
          <el-form-item label="地图">
            <div id="addMap" style="min-height: 400px;width: 100%;"></div>
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="addForm.longitude" readonly></el-input>
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="addForm.latitude" readonly></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="pca">
            <v-distpicker :province="addForm.province" :city="addForm.city" :area="addForm.area" @province="onChangeAddProvince"
              @city="onChangeAddCity" @area="onChangeAddArea"></v-distpicker>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-row>
              <el-col :span="18">
                <el-input v-model="addForm.address" maxlength="255" show-word-limit clearable></el-input>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="searchAdd('addForm')">搜索</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="addForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="detail">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" maxlength="255" show-word-limit clearable v-model="addForm.detail">
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="管理员" prop="bind_id">
            <el-select v-model="addForm.bind_id" placeholder="请选择管理员" clearable>
              <el-option v-for="(item) in adminList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="司机" v-if="addForm.type !== 2" prop="driver_id">
            <el-select v-model="addForm.driver_id" placeholder="请选择司机" clearable>
              <el-option v-for="(item) in driverList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible','addForm')" size="small">添 加</el-button>
        </span>
      </el-dialog>

      <!-- <el-dialog title="绑定司机" :visible.sync="driverVisible" :before-close="handleClose('driverForm')" width="400px">
        <el-form ref="driverForm" :model="driverForm" label-width="80px" :rules="rules">
          <el-form-item label="司机" prop="driver_id">
            <el-select v-model="driverForm.driver_id" placeholder="请选择司机" clearable>
              <el-option v-for="(item) in driverList" :key="item.id" :label="item.name + '-'+item.role_name" :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.role_name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('driverVisible', 'driverForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('driverVisible','driverForm')" size="small">添 加</el-button>
        </span>
      </el-dialog> -->
    </el-scrollbar>
  </div>
</template>
<script>
import {
  getOrgList,
  getOrgOnly,
  addOrg,
  changeOrgStatus,
  editOrg,
  delOrg
  // , getAdmin, bindOrgDriver, unbindOrgDriver
} from '@/network/api.js'

export default {
  name: 'org',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        status: ''
      },
      table: [],
      count: 0,

      editForm: {
        id: 0,
        name: '', // 名称
        longitude: 0, // 经度
        latitude: 0, // 纬度
        province: '', // 省
        city: '', // 市
        area: '', // 区
        address: '', // 详细地址
        detail: '', // 描述
        bind_id: ''
      },
      editVisible: false, // 编辑

      // 添加表单
      addForm: {
        name: '', // 名称
        longitude: 0, // 经度
        latitude: 0, // 纬度
        province: '', // 省
        city: '', // 市
        area: '', // 区
        address: '', // 详细地址
        detail: '', // 描述
        bind_id: ''
      },
      addVisible: false, // 添加

      // 司机表单
      driverForm: {
        id: 0,
        driver_id: ''
      },
      driverVisible: false,
      driverList: [], // 司机列表

      map: {}, // 地图
      markersArray: [], //
      rules: {
        name: [{ required: true, message: '名称必须', trigger: 'blur' }],
        longitude: [{ required: true, message: '经度必须', trigger: 'blur' }],
        latitude: [{ required: true, message: '纬度必须', trigger: 'blur' }],
        address: [{ required: true, message: '详细地址必须', trigger: 'blur' }],
        detail: [{ required: true, message: '详情必须', trigger: 'blur' }],
        bind_id: [{ required: true, message: '绑定必须', trigger: 'blur' }],
        driver_id: [{ required: true, message: '司机必须', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    // 每页条数变化
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.search()
    },
    async search(pageInit = false) {
      try {
        if (pageInit === true) {
          this.searchForm.page = 1
        }
        const rtn = await getOrgList(this.searchForm)
        this.table = rtn.list
        this.count = rtn.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加
    async add() {
      try {
        this.addForm.longitude = 104.04334259059397 // 经度
        this.addForm.latitude = 30.641865646608366 // 纬度
        this.addForm.province = '四川省' // 省
        this.addForm.city = '成都市' // 市
        this.addForm.area = '武侯区' // 区
        this.addVisible = true
        this.$nextTick(() => {
          this.makeMap(parseFloat(this.addForm.latitude), parseFloat(this.addForm.longitude), 'addMap', 'addForm')
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    onChangeAddProvince(a) {
      this.addForm.province = a.value
    },
    onChangeAddCity(a) {
      this.addForm.city = a.value
    },
    onChangeAddArea(a) {
      this.addForm.area = a.value
    },
    onChangeEditProvince(a) {
      this.editForm.province = a.value
    },
    onChangeEditCity(a) {
      this.editForm.city = a.value
    },
    onChangeEditArea(a) {
      this.editForm.area = a.value
    },
    // 创建地图
    makeMap(latitude, longitude, type, formName) {
      // 设置中心点
      const center = new window.qq.maps.LatLng(latitude, longitude)
      // 绘制地图
      this.map = new window.qq.maps.Map(document.getElementById(type), {
        center: center,
        zoom: 15
      })
      this.clearMarkers()
      const marker = new window.qq.maps.Marker({
        position: center,
        map: this.map
      })
      this.markersArray.push(marker)
      window.qq.maps.event.addDomListener(this.map, 'click', event => {
        this.clearMarkers()
        const marker = new window.qq.maps.Marker({
          position: event.latLng,
          map: this.map
        })
        this[formName].longitude = event.latLng.lng
        this[formName].latitude = event.latLng.lat
        this.markersArray.push(marker)
      })
    },
    clearMarkers() {
      if (this.markersArray) {
        for (const i in this.markersArray) {
          this.markersArray[i].setMap(null)
        }
        this.markersArray.length = 0
      }
    },
    // 搜索地址
    searchAdd(formName) {
      if (this[formName].province === '省' || this[formName].city === '市' || this[formName].area === '区' || this[formName].address === '') {
        return this.$message.error('请先选择填写完整地址')
      }
      this.clearMarkers()
      window.geocoder = new window.qq.maps.Geocoder({
        complete: result => {
          this.map.setCenter(result.detail.location)
          this[formName].longitude = result.detail.location.lng
          this[formName].latitude = result.detail.location.lat
          const marker = new window.qq.maps.Marker({
            map: this.map,
            position: result.detail.location
          })
          this.markersArray.push(marker)
        }
      })
      window.geocoder.getLocation(`${this[formName].province}${this[formName].city}${this[formName].area}${this[formName].address}`)
    },
    // 修改状态
    changeStatus(ev) {
      let msg = ''
      let oldStatus = ''
      switch (ev.status) {
        case 1:
          msg = '您确定要启用该分拣中心吗?'
          oldStatus = 2
          break
        case 2:
          msg = '此操作将禁用该分拣中心, 是否确定?'
          oldStatus = 1
          break
        default:
          return this.$message.error('不可用的操作')
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(async () => {
          try {
            await changeOrgStatus({ id: ev.id, status: ev.status })
          } catch (e) {
            ev.status = oldStatus
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          ev.status = oldStatus
          this.$message.warning('您已取消操作')
        })
    },
    // 删除
    del(id) {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await delOrg({ id })
            this.search()
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          this.$message.warning('您已取消操作')
        })
    },
    // 编辑
    async edit(id) {
      try {
        const rtn = await getOrgOnly({ id })
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn.info
          this.adminList = rtn.adminList
          this.makeMap(parseFloat(this.editForm.latitude), parseFloat(this.editForm.longitude), 'editMap', 'editForm')
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // // 绑定司机
    // async bindDriver(id) {
    //   try {
    //     this.driverForm.id = id
    //     const rtn = await getAdmin({})
    //     this.driverVisible = true
    //     this.$nextTick(() => {
    //       this.driverList = rtn
    //     })
    //   } catch (e) {
    //     this.$message.error(e.message)
    //   }
    // },
    // // 解绑司机
    // async unbindDriver(row) {
    //   this.$confirm('您确定要解绑司机吗？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(async () => {
    //       try {
    //         await unbindOrgDriver({ id: row.id, driver_id: row.driver_id })
    //         this.search()
    //       } catch (e) {
    //         this.$message.error(e.message)
    //       }
    //     })
    //     .catch(() => {
    //       this.$message.warning('您已取消操作')
    //     })
    // },
    handleCommand(command) {
      switch (command.cmd) {
        case 'del':
          this.del(command.id)
          break
        case 'edit':
          this.edit(command.id)
          break
        case 'bindDriver':
          this.bindDriver(command.id)
          break
        case 'unbindDriver':
          this.unbindDriver(command.row)
          break
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose(formName) {
      return done => {
        this.$refs[formName].clearValidate()
        this.$refs[formName].resetFields()
        done()
      }
    },
    // 取消按钮
    close(visibleName, formName) {
      this.$refs[formName].clearValidate()
      this.$refs[formName].resetFields()
      this[visibleName] = false
    },
    send(visibleName, formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          switch (formName) {
            case 'editForm': // 编辑
              if (this[formName].province === '省' || this[formName].city === '市' || this[formName].area === '区' || this[formName].address === '') {
                return this.$message.error('请先选择填写完整地址')
              }
              try {
                await editOrg(this.editForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'addForm': // 添加
              if (this[formName].province === '省' || this[formName].city === '市' || this[formName].area === '区' || this[formName].address === '') {
                return this.$message.error('请先选择填写完整地址')
              }
              try {
                await addOrg(this.addForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            // case 'driverForm': // 司机
            //   try {
            //     await bindOrgDriver(this.driverForm)
            //     this.close(visibleName, formName)
            //     this.search()
            //   } catch (e) {
            //     this.$message.error(e.message)
            //   }
            //   break
          }
        } else {
          this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.pwrap {
  height: 400px;

  overflow-y: auto;

  position: fixed;

  left: 0;

  bottom: 0;

  width: 100%;
}

/deep/ .pwrap .distpicker-address-wrapper {
  color: #999;
}

/deep/ .pwrap .address-header {
  position: fixed;

  bottom: 400px;

  width: 100%;

  background: #000;

  color: #fff;
}

/deep/ .pwrap .address-header ul li {
  flex-grow: 1;

  text-align: center;
}

/deep/ .pwrap .address-header .active {
  color: #fff;

  border-bottom: #666 solid 8px;
}

/deep/.pwrap .address-container .active {
  color: #000;
}
.expand-class {
  font-size: 16px;
}
</style>
